package com.kuaiditu.assistant.ui.main;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.kuaiditu.assistant.R;
import com.kuaiditu.assistant.api.ParamsAnalog;
import com.kuaiditu.assistant.api.assistant_api.AssistantApi;
import com.kuaiditu.assistant.api.assistant_api.respone.TaskSquareRes;
import com.kuaiditu.assistant.base.BaseFragment;
import com.kuaiditu.assistant.entity.ExpressCom;
import com.kuaiditu.assistant.entity.TaskSquareEn;
import com.kuaiditu.assistant.event.RefreshEvent;
import com.kuaiditu.assistant.module.retrofit.ProgressSubscriber;
import com.kuaiditu.assistant.ui.scan.DeliveryScanActivity;
import com.kuaiditu.assistant.ui.scan.SignScanActivity;
import com.kuaiditu.assistant.ui.thirdparty.STLoginActivity;
import com.kuaiditu.assistant.ui.thirdparty.YDLoginActivity;
import com.kuaiditu.assistant.ui.thirdparty.YTLoginActivity;
import com.kuaiditu.assistant.ui.thirdparty.ZTLoginWebActivity;
import com.kuaiditu.assistant.util.LogUtil;
import com.kuaiditu.assistant.util.OrderStateUtil;
import com.kuaiditu.assistant.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;


public class AwaitTaskFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    protected String title = "待完成任务";
    @BindView(R.id.rv_await_task)
    RecyclerView mRvAwaitTask;
    @BindView(R.id.swiper)
    SwipeRefreshLayout swiper;
    Unbinder unbinder;

    int page = 1;
    int count = 0;
    private AwaitTaskAdapter mAwaitTaskAdapter;
    private List<TaskSquareEn> mTasks = new ArrayList<>();

    AssistantApi mAssistantApi;

    private boolean isRefresh;

    private ParamsAnalog mParamsAnalog;


    private boolean needRefresh = true;



    @Override
    public void initInjector() {
        mAssistantApi = getApplicationComponent().getApiManager().getAssistantApi();
        mParamsAnalog = getApplicationComponent().getParamsAnalog();
    }

    @Override
    public int initContentView() {
        return R.layout.fragment_await_task;
    }

    @Override
    public void getBundle(Bundle bundle) {

    }

    @Override
    public void initUI(View v) {

        EventBus.getDefault().register(this);

        unbinder = ButterKnife.bind(this, v);
        mRvAwaitTask.setLayoutManager(new LinearLayoutManager(mContext));
        mRvAwaitTask.setAdapter(mAwaitTaskAdapter = new AwaitTaskAdapter(mTasks, getApplicationComponent()));
        mAwaitTaskAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                AwaitTaskAdapter awaitTaskAdapter = (AwaitTaskAdapter) adapter;
                TaskSquareEn taskSquareEn = awaitTaskAdapter.getData().get(position);


                if (taskSquareEn.getOperator() != null) {
                    switch (view.getId()) {
                        case R.id.img_camera_take_delivery:

                            if (taskSquareEn.getOrder_status().equals(OrderStateUtil.COURIERPICK)) {

                                ARouter.getInstance().build(DeliveryScanActivity.PATH)
                                        .withInt("task_id", taskSquareEn.getOrder_id())
                                        .withInt("express_com_id", taskSquareEn.getOrder_netsite().getNetsite_expressCompanyId())
                                        .navigation(getActivity(), 1001);

                            } else {
                                ToastUtil.showToast("添加派件已完成");
                            }

                            break;
                        case R.id.img_camera_send_delivery:
                            if (taskSquareEn.getOrder_status().equals(OrderStateUtil.COURIERADDORDER)) {
                                ARouter.getInstance().build(SignScanActivity.PATH)
                                        .withInt("task_id", taskSquareEn.getOrder_id())
                                        .withInt("express_com_id", taskSquareEn.getOrder_netsite().getNetsite_expressCompanyId())
                                        .navigation(getActivity(), 1001);
                            } else {
                                ToastUtil.showToast("请先完成添加派件");
                            }

                            break;

                        case R.id.btn_thirdparty:
                           thirdLogin(taskSquareEn);
                            break;
                    }
                } else {
                    ToastUtil.showToast("请先登录网点账号");
                    thirdLogin(taskSquareEn);
                }
            }
        });
        swiper.setOnRefreshListener(this);
    }

    private void thirdLogin(TaskSquareEn taskSquareEn) {
        switch (taskSquareEn.getOrder_netsite().getNetsite_expressCompanyId()) {
            case ExpressCom.EXPRESS_COM_CODE_YD:
                ARouter.getInstance().build(YDLoginActivity.PATH)
                        .withInt("task_id", taskSquareEn.getOrder_id())
                        .navigation(getActivity(), 1002);
                break;
            case ExpressCom.EXPRESS_COM_CODE_ZT:
                ARouter.getInstance().build(ZTLoginWebActivity.PATH)
                        .withInt("task_id", taskSquareEn.getOrder_id())
                        .navigation(getActivity(), 1002);
                break;
            case ExpressCom.EXPRESS_COM_CODE_YT:
                ARouter.getInstance().build(YTLoginActivity.PATH)
                        .withInt("task_id", taskSquareEn.getOrder_id())
                        .navigation(getActivity(), 1002);
                break;
            case ExpressCom.EXPRESS_COM_CODE_ST:
                ARouter.getInstance().build(STLoginActivity.PATH)
                        .withInt("task_id", taskSquareEn.getOrder_id())
                        .navigation(getActivity(), 1002);
                break;
            default:
                ARouter.getInstance().build(YDLoginActivity.PATH)
                        .withInt("task_id", taskSquareEn.getOrder_id())
                        .navigation(getActivity(), 1002);
                break;
        }
    }


    @Override
    public void initData() {

    }

    @Override
    public String getTitle() {
        return title;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    private void fetchMyTask() {
        mAssistantApi.fetchPersonTask(page, AssistantApi.TYPE_TASK_NOT_END)
                .subscribe(new ProgressSubscriber<TaskSquareRes>(mContext) {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onNext(TaskSquareRes taskSquareRes) {
                        isRefresh = false;
                        mTasks.addAll(taskSquareRes.getListOrder());
                        mAwaitTaskAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFinish() {
                        swiper.setRefreshing(false);
                    }
                });
    }

    @Override
    public void onRefresh() {
        swiper.setRefreshing(true);
        mTasks.clear();
        page = 1;
        fetchMyTask();
        isRefresh = true;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        LogUtil.e("requestCode = " + requestCode);

        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1001 && resultCode == Activity.RESULT_OK) {
            onRefresh();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        if (needRefresh) {
            onRefresh();
            needRefresh = false;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void NeedRefresh(RefreshEvent event) {
        this.needRefresh = true;
        LogUtil.e("NeedRefresh");
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
